<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
 * PHP version 5
 *
 * This source file is subject to version 2.1 of the GNU Lesser General Public
 * License, that is bundled with this package in the file COPYING, available
 * through the world wide web at the following URI:
 * http://www.gnu.org/copyleft/lesser.html.
 *
 *Razred za uporavljanje uporabnikov v bazi. Vsebuje tudi metode za administracijo, oz brisanje uporabnikov. Vse metode za vloge uporabnikov se nahajajo v datoteki RoleDAO.php.
 *
 * @package    User
 * @author     Aljaz Srebrnic
 * @author     Enzo Pavletic
 * @copyright  2004-2007 The ZNF Development Team
 * @license    LGPL License 2.1 <http://www.gnu.org/copyleft/lesser.html>
 * @link       http://www.zeronotice.org
 */

require_once('ZNF/Business/MDB2.php');
require_once('ZNF/Util/Utility.php');

class User_Business_UserDAO
{

    private $_db = null;
    private $_tablePrefix = null;

/**
 *Konstruktor dobi povezavo z bazo in nastavi charset kot utf-8, da ne bo prislo do problemov s stresicami.
 */

    public function __construct()
    {
        $this->_db = ZNF_Business_MDB2::getInstance();
        $this->_tablePrefix = ZNF_Business_MDB2::getTablePrefix();
		$this->_db->setCharset('utf8');
    }

/**
 *Metoda doda uporabnika v bazo. Metoda tudi asocira uporabniku stadnard vlogo, ki predstavlja vlgo registriranega uporabnika.
 *Default vrednosti so:
 *<ul>
 *<li>theme = default</li>
 *<li>lang = si</li>
 *<li>locale = si_SI</li>
 *</ul>
 */
    public function insert($username, $password, $name, $surname, $phone, $cell,
			   $email, $icq, $msn, $skype, $theme = 'default', $lang = 'si', $locale = 'si_SI')
    {
        $insertUser = 'INSERT INTO ' . $this->_tablePrefix . "User(username, password, name, surname, phone, cell, email, icq, msn, skype, theme, lang, locale)
                VALUES ('$username', md5('$password'), '$name', '$surname', '$phone', '$cell', '$email', '$icq', '$msn',
                '$skype', '$theme', '$lang', '$locale')";

	$res = $this->_db->beginTransaction();			//Zacnemo s transakcijo. Ce bo prislo medtem do napake, bomo vse spremembe razveljavili od te tocke dalje
	$res = $this->_db->exec($insertUser);			//Vnesemo uporabnika v tabelo.
        if (PEAR::isError($res)) {				//Pregledamo, ali je prislo do napake
	    $this->_db->rollback();				//Raazveljavimo napake
            throw new User_Business_UserDAOException('errorUserInsert - '. $res->getMessage());
        }
	$userId = $this->_db->lastInsertID('User');		//Shranimo id uporabnika, ki smo ga komaj vnesli v bazo
	if(PEAR::isError($userId)){
	    $this->_db->rollback();
	    throw new User_Business_User_Business_RoleDAOException('errorUserRoleAssociation - '. $userId->getMessage());
	}
	$associateRole = 'INSERT INTO ' . $this->_tablePrefix . "UserRoleAssociation(userId, userRoleName)
			VALUES ('$userId', 'standard')";
	$res = $this->_db->exec($associateRole);		//Asociramo standard vlogo komaj vnesenemu uporabniku
        if (PEAR::isError($res)) {
	    $this->_db->rollback();
            throw new User_Business_UserDAOException('errorUserRoleAssociation - '. $res->getMessage());
        }
	$this->_db->commit();
    }

    /**
     *Metoda posodobi podatke o uporabniku v bazi. Poisce ga le po id-ju.
     *
     */

    public function update($id, $name, $surname, $phone, $cell, $email, $icq, $msn, $skype, $comment = "", $active = 1, $password = null, $theme = 'default', $lang = 'si', $locale = 'si_SI')
    {
        $sql = 'UPDATE ' . $this->_tablePrefix . "User SET
                    name='$name',
                    surname='$surname',
                    phone='$phone',
                    cell='$cell',
                    email='$email',
                    icq='$icq',
                    msn='$msn',
                    skype='$skype',
                    theme='$theme',
                    lang='$lang',
                    locale='$locale',
		    		comment='$comment', ";
		if($password != null){
			$sql = $sql . "password=md5('$password'),";
		}
		$sql = $sql . " active='$active'
            		WHERE id='$id'";
        $res = $this->_db->exec($sql);
        if (PEAR::isError($res)) {
            throw new User_Business_UserDAOException('errorUserUpdate - '. $res->getMessage() . " - " . $sql);
        }
    }

    /**
    *Metoda zbrise uporabnika z baze.
    *@param integer $id Id uporabnika, ki ga zelimo zbrisati.
    */

    public function delete($id)
    {
	$delete = 'DELETE FROM ' . $this->_tablePrefix . "User WHERE id='$id'";
	$res = $this->_db->exec($delete . $sql);
        if (PEAR::isError($res)) {
            throw new User_Business_UserDAOException('errorUserDelete - '. $res->getMessage());
        }
    }

    /**
     *Metoda zbrise array uporabnikov
     *@param array $ids Id-ji uporabnikov, ki jih zelimo izbrisati.
     *
     **/

     public function deleteUsers($ids){
     	$this->_db->beginTransaction();
     	foreach($ids as $id){
     		try{
     			$this->delete($id);
     		} catch(User_Business_UserDAOException $e){
     			$this->_db->rollback();						//Ce pride do napake, rollback-iram izbrise
     			throw $e;									//in propagiram exception
     		}
     	}
     	$this->_db->commit();
     }

    /**
     *Metoda za login. Poisce, ali uporabnik obstaja v bazi in ce je njegovo geslo pravilno.
     *Hkrati pa posodobi informacije o zadnjem loginu in doda 1 logincount-u.
     *@param string $username Uporabnisko ime uporabnika, ki se bo prijavil.
     *@param string $password Geslo uporabnika.
     *@return Vse podatke o uporabniku.
     */

    public function authUser($username, $password)
    {
        $sql = 'SELECT * FROM ' . $this->_tablePrefix . "User WHERE username='$username' AND password=md5('$password')";
        $row = $this->_db->queryRow($sql);

        if (PEAR::isError($row)) {
            throw new User_Business_UserDAOException('errorUserLoad - '. $row->getMessage());
        }
	$sql = 'UPDATE ' . $this->_tablePrefix . "User SET lastlogin=NOW(), logincount=logincount+1
											WHERE username='$username' AND password=md5('$password')";
	$upd = $this->_db->exec($sql);
	if (PEAR::isError($upd)) {
	  throw new User_Business_UserDAOException('errorUserLoad - '. $upd->getMessage());
        }
	if(count($row) > 0)
	  $row = ZNF_Util_Utility::stripAllSlashes($row);
	
        return $row;
    }

    /**
     *Metoda isce uporabnike po usernamu in priimku
     *@param string $text Niz znakov, po katerem bomo iskali uporabnika
     *@return array z id-jem, imenom, priimkom in usernamem uporabnika
     **/
    
    public function search($text){
      $sql = 'SELECT id, username, name, surname FROM ' . $this->_tablePrefix . "User WHERE username LIKE '$text%' OR surname LIKE '$text%'";
      
      $res = $this->_db->queryAll($sql);
      
      if (PEAR::isError($res)) {
	throw new User_Business_UserDAOException('errorUserList - '. $res->getMessage());
      }
      return ZNF_Util_Utility::stripAllSlashes($res);
    }

    /**
     *Metoda vrne vse podatke o uporabniku, identificiranem z ID-jem.
     *@param integer $id Id uporabnika, o katerem zelimo prejeti vse podatke.
     *@return array Tabela podatkov o uporabniku.
     **/
    public function getById($id)
    {
      $sql = 'SELECT * FROM ' . $this->_tablePrefix . "User WHERE id='$id'";
      $row = $this->_db->queryRow($sql);
      if (PEAR::isError($row)) {
	throw new User_Business_UserDAOException('errorUserLoad - '. $row->getMessage());
      }
      if(count($row) > 0)
	$row = ZNF_Util_Utility::stripAllSlashes($row);
      return $row;
    }

    /**
     *Metoda vrne podatke danega uporabnika.
     *@param string $username Uporabisko ime, za katerega zelimo izvedeti vse podatke.
     *@return Podatki o uporabniku.
     **/

    public function getByUsername($username)
    {
        $sql = 'SELECT * FROM ' . $this->_tablePrefix . "User WHERE username='$username'";
        $row = $this->_db->queryRow($sql);
        if (PEAR::isError($row)) {
            throw new User_Business_UserDAOException('errorUserLoad - '. $row->getMessage());
        }
	if(count($row) > 0)
	  $row = ZNF_Util_Utility::stripAllSlashes($row);
        return $row;
    }

    /**
     *Metoda pregleda, ali je dano uporabnisko ime ze zasedeno.
     *Kot argument prejme uporabnisko ime in vrne true, ce je uporabnisko ime se prosto.
     *@param string $username Uporabnisko ime, za katerega zelimo preveriti, li je se prosto.
     *@return true, ce je uporabnisko ime prosto.
     */

    public function check($username)
    {
        $sql = 'SELECT * FROM ' . $this->_tablePrefix . "User WHERE username='$username'";
        $rows = $this->_db->queryAll($sql);
        if (PEAR::isError($rows)) {
            throw new User_Business_UserDAOException('errorUserAvailableCheck - '. $rows->getMessage());
        }

        if(count($rows) > 0)
            return false;
        else
            return true;
    }

    /**
     *Metoda spremeni geslo danega uporabnika
     *@param string $username Uporabnisko ime
     *@param string $password novo geslo
     *@return void
     **/

    public function updatePassword($username, $password){
	$sql = 'UPDATE ' . $this->_tablePrefix . "User SET password=md5('$password') WHERE username='$username'";
	$res = $this->_db->exec($sql);
	if (PEAR::isError($res)) {
            throw new User_Business_UserDAOException('errorUserLoad - '. $res->getMessage());
        }
    }

    /**
     *Metoda vrne seznam uporabnikov
     *@param int $offset Offset liste uporabnikov
     *@param int $limit  Določi koliko uporabnikov bomo prikazali na stran
     *@return Array z uporabniki
     */

    public function getAll($offset, $limit){
	$sql = 'SELECT * FROM ' . $this->_tablePrefix . "User ORDER BY id asc LIMIT $limit OFFSET $offset";
	$res = $this->_db->queryAll($sql);
	if (PEAR::isError($res)) {
            throw new User_Business_UserDAOException('errorUserList - '. $res->getMessage());
        }
	return ZNF_Util_Utility::stripAllSlashes($res);
    }

    /**
     * Metoda vrne stevilo uporabnikov v bazi
     *@return stevilo vseh uporabnikov, prisotnih v bazi.
     **/

    public function countUsers(){
      $sql = 'SELECT COUNT(*) AS total FROM ' . $this->_tablePrefix . 'User';
      $res = $this->_db->queryRow($sql);
      if (PEAR::isError($res)) {
	throw new User_Business_UserDAOException('errorUserList - '. $res->getMessage());
      }
      return $res['total'];
    }


    public function __destruct()
    {
    }

}

class User_Business_UserDAOException extends Exception
{
}

?>
